/**
 * .disableTextSelect - Disable Text Select Plugin
 *
 * Version: 1.0
 * Updated: 2007-08-11
 *
 * Used to stop users from selecting text
 *
 * Copyright (c) 2007 James Dempster (letssurf@gmail.com, http://www.jdempster.com/category/jquery/disabletextselect/)
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 **/

/**
 * Requirements:
 * - jQuery (John Resig, http://www.jquery.com/)
 **/
(function($) {
    if ($.browser.mozilla) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).css({
                    'MozUserSelect' : 'none'
                });
            });
        };
    } else if ($.browser.msie) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).bind('selectstart', function() {
                    return false;
                });
            });
        };
    } else {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).mousedown(function() {
                    return false;
                });
            });
        };
    }
})(jQuery);

// End Disable Text Select Plugin

$(document).ready(function() {
	//Tickets.add();
});

var Tickets = {
	
	settings : {
		top: 30, // %
		left: 30, // %
		width: 150, // px
		height: 150, // px
		minWidth: 30, // px
		minHeight: 30, // px
		totalBorderWidth: 2 // px, общая ширина границ обычного тикета 
	},
	busy : false,
	photoId: null,
	photoOwnerId: null,
	ticketsSizes: [],
	
	put: function(params, index, cntTickets) {
		var ticketsWrapper = $('#photo_tickets');
		var ticketsList = $('#tickets_list');
		
		Tickets.ticketsSizes.push([parseInt(params.width+params.height), params.id]);
		
		//
		//
		// Add ticket area
		
		var newTicket = $('<div>')
			.attr('id', 'ticket_'+params.id)
			.addClass('item')
			.css({
				top: params.top+'px',
				left: params.left+'px'
			})
			.mouseover(function() {
				$(this).addClass('active');
				
				$('#photo_tickets > .item:not([id=ticket_'+params.id+'])').addClass('disactive');
			})
			.mouseout(function() {
				$(this).removeClass('active');
				
				$('#photo_tickets > .item').removeClass('disactive');
			});
			
		var area = $('<div>')
			.addClass('area')
			.css({
				width: params.width+'px',
				height: params.height+'px'
			});
			
		var label = $('<div>')
			.addClass('label')
			.append(
				$('<a>')
					.attr('href', GlobalSettings.baseURI+'/user/'+params.userLogin)
					.text(params.userLogin)
			);
			
		newTicket
			.append($('<div>').addClass('area-wrapper').append(area))
			.append(label);
			
		ticketsWrapper.append(newTicket);
		
		//
		//
		// Add ticket link
		
		var ticketLinkWrapper = $('<span>')
			.attr('id', 'ticket_link_'+params.id)
			.mouseover(function() {
				$('#ticket_'+params.id)
					.addClass('light')
					.find('.area-wrapper > .area').css({
						backgroundImage: 'url("'+$('#photoimg').attr('src')+'")',
						backgroundPosition: '-'+params.left+'px -'+params.top+'px'
					});
				
				$('#photo_tickets > .black').show();
			})
			.mouseout(function() {
				$('#ticket_'+params.id)
					.removeClass('light')
					.find('.area-wrapper > .area').css({
						backgroundImage: 'none',
						backgroundPosition: ''
					});
				
				$('#photo_tickets > .black').hide();
			});
		
		var ticketLink = $('<a>')
			.attr('href', GlobalSettings.baseURI+'/user/'+params.userLogin)
			.text(params.userLogin);
			
		ticketLinkWrapper.append(ticketLink);
		
		if (Tickets.photoOwnerId == GlobalSettings.userId || params.userId == GlobalSettings.userId) {
			ticketLinkWrapper.append(' <span class="control">(<a href="#" onclick="Tickets.delete('+params.id+'); return false;">удалить</a>)');
		}
		
		if (index !== true && index+1 < cntTickets) {
			ticketLinkWrapper.append(', ');
		}
		
		ticketsList.append(ticketLinkWrapper);
	},
	
	load: function() {
		$.ajax ({
			url: baseURI + '/photos/ajax_photo_tickets/'+this.photoId,
			dataType: 'xml',
			type: 'get',
			error: function () { new Error("Ошибка при загрузке списка отметок!");  },
			success: function (xml) {
				Tickets.onLoaded(xml);
			}
		});
	},
	
	onLoaded: function(xml) {
		var objects = $(xml).find('data > response > object');
		
		var sizeSortableList = [];
		
		objects.each(function(index) {
			Tickets.put({
				top: $(this).find('property[name=y] > value').text(),
				left: $(this).find('property[name=x] > value').text(),
				width: $(this).find('property[name=width] > value').text(),
				height: $(this).find('property[name=height] > value').text(),
				userLogin: $(this).find('property[name=user_login] > value').text(),
				userId: $(this).find('property[name=user_id] > value').text(),
				id: $(this).attr('id'),
				ticketId: 'ticket_'+$(this).attr('id')
			}, index, objects.length);
		});
		
		this.setTicketsZIndex();
		
		//
		//
		// Подсветка тикетов при наведении на фото
		$('#photo_tickets')
			.mouseover(function() {
				$(this).children('.item:not(.temp)').addClass('hightlight');
			})
			.mouseout(function() {
				$(this).children('.item').removeClass('hightlight');
			});
	},
	
	// Выставление тикетам z-index исходя из их размера, для того чтобы работали пересеченные области
	setTicketsZIndex: function() {
		var t = true;
		while(t) {
			t = false;
			for (i = 0; i < this.ticketsSizes.length-1; ++i) {
				if (this.ticketsSizes[i][0] > this.ticketsSizes[i+1][0]) {
					var temp = this.ticketsSizes[i+1];
					this.ticketsSizes[i+1] = this.ticketsSizes[i];
					this.ticketsSizes[i] = temp;
					t = true;
				}
			}
		}
		
		this.ticketsSizes.reverse();
		
		for (i = 0; i < this.ticketsSizes.length; ++i) {
			$('#ticket_'+this.ticketsSizes[i][1]).css('z-index', 200+i);
		}
	},
	
	delete: function(id) {
		$('#ticket_'+id).remove();
		$('#ticket_link_'+id).remove();
		
		$.ajax ({
			url: baseURI + '/photos/ajax_delete_ticket/'+id+'?scode='+GlobalSettings.scode,
			dataType: 'xml',
			type: 'get',
			error: function () { new Error("Ошибка при удалении отметки!");  },
			success: function (xml) {
				if ($(xml).find('result').text()) {
					new Message('Отметка удалена');
				} else {
					new Error("Ошибка при удалении отметки!");
				}
			}
		});
	},
	
	close: function() {
		$('#photo_ticket_temp').remove();
		$('#photo_tickets > .black').hide();
		$('#photo_tickets > .item').show();
		$('#ticket_form').remove();
		this.busy = false;
	},
	
	add : function() {
		if (this.busy) {
			return false;
		}
		
		this.busy = true;
		$('#photo_tickets > .item').hide();
		
		var __self = this;
		
		var ticketsWrapper = $('#photo_tickets');
		var ticketsWrapperWidth = ticketsWrapper.width();
		var ticketsWrapperHeight = ticketsWrapper.height();
		
		var ticket = $('<div>')
			.attr('id', 'photo_ticket_temp')
			.addClass('item')
			.addClass('temp')
			.css({
				top: Math.floor(ticketsWrapperHeight/100*this.settings.top)+'px',
				left: Math.floor(ticketsWrapperWidth/100*this.settings.left)+'px',
				display: 'none'
			});
			
		var area = $('<div>')
			.addClass('area')
			.css({
				background: 'url("'+$('#photoimg').attr('src')+'")',
				width: this.settings.width+'px',
				height: this.settings.height+'px'
			})
			.mousedown(function(e) {
				__self.startMove(e);
			})
			.mouseup(function() {
				__self.stopMove(); 
			});
			
		var resize = $('<div>')
			.addClass('resize')
			.append($('<div>').addClass('inner'));
	
		ticket
			.append(
				resize.clone()
					.addClass('nw')
					.mousedown(function() {
						__self.startResize('nw');
					})
			)
			.append(
				resize.clone()
					.addClass('ne')
					.mousedown(function() {
						__self.startResize('ne');
					})
			)
			.append(
				resize.clone()
					.addClass('se')
					.mousedown(function() {
						__self.startResize('se');
					})
			)
			.append(
				resize.clone()
					.addClass('sw')
					.mousedown(function() {
						__self.startResize('sw');
					})
			);
			
		ticket
			.append(area)
			.show();	
		
		$('#photo_tickets').append(ticket);
		
		$('#photo_tickets > .black').show();
			
		this.updatePhotoCrop();
		
		$(document).mouseup(function() {
			$(this)
				.unbind('mousemove', __self.resize)
				.unbind('mousemove', __self.move);
		});
		
		// Form
		var form = $('<div>')
			.attr('id', 'ticket_form')
			.addClass('ticket-form')
			.html(
				'<div class="wrapper">'+
					'<div class="inner">'+
						'<h1><span>Выберите друга</span></h1>'+
						'<div class="body">'+
							'<ul id="ticket_friends_list" class="friends-list"></ul>'+
							'<div class="buttons"><input type="button" value="Отмена" onclick="Tickets.close();" /></div>'+
						'</div>'+
					'</div>'+
				'</div>'
			);
			
		$(document.body).append(form);
		
		this.updateFormPosition();
		
		this.loadFriendsList();
	},
	
	updateFormPosition: function() {
		var ticket = $('#photo_ticket_temp');
		
		$('#ticket_form').css({
			top: ticket.offset().top + 'px',
			left: (ticket.offset().left + ticket.children('.area').width() + 20)+'px'
		});
	},
	
	loadFriendsList: function() {
		$.ajax ({
			url: baseURI + '/users/ajax_xml_get_user_friends/',
			dataType: 'xml',
			type: 'get',
			error: function () { new Error("Ошибка при загрузке списка друзей!");  },
			beforeSend: function() {
				$('#ticket_friends_list').addClass('loading');
			},
			complete: function() {
				$('#ticket_friends_list').removeClass('loading');
			},
			success: function (xml) {
				var ul = $('#ticket_friends_list');
				
				ul.append($('<li>')
					.addClass('first')
					.append(
						$('<a>')
							.attr('href', '#')
							.text('Я')
							.click(function() {
								Tickets.addFriend(userId, 'Я');
								return false;
							})
					)
				);
				
				$(xml).find('object').each(function() {
					var login = $(this).find('property[name=user_login] > value').text();
					var __self = this;
					
					ul.append(
						$('<li>').append(
							$('<a>')
								.attr('href', '#')
								.text(login)
								.click(function() {
									Tickets.addFriend($(__self	).find('property[name=friend_id] > value').text(), login);
									return false;
								})
						)
					);
				});
			}
		});
	},
	
	addFriend: function(userId, userLogin) {
		var ticketPosition = $('#photo_ticket_temp').position();
		var area = $('#photo_ticket_temp > .area');
		var areaWidth = area.width();
		var areaHeight = area.height();
		
		this.close();
		
		$.ajax ({
			url: baseURI + '/photos/ajax_add_ticket/',
			data: 'data[new][photo_id]='+this.photoId+'&data[new][user_id]='+userId+'&data[new][x]='+ticketPosition.left+'&data[new][y]='+ticketPosition.top+'&data[new][width]='+areaWidth+'&data[new][height]='+areaHeight,
			dataType: 'xml',
			type: 'post',
			error: function () { new Error("Ошибка при добавлении отметки!");  },
			success: function (xml) {
				if (!$(xml).find('result').text()) {
					new Error("Ошибка при добавлении отметки!");
					return;
				}
				
				var ticketId = $(xml).find('id').text();
				var x = ticketPosition.top;
				var y = ticketPosition.left;
				var width = areaWidth;
				var height = areaHeight;
				
				// Запрос для получения логина пользователя
				$.ajax ({
					url: baseURI + '/photos/ajax_get_ticket/'+ticketId,
					dataType: 'xml',
					type: 'get',
					success: function (xml) {
						var object = $(xml).find('data > response > object');
						
						Tickets.put({
							top: x,
							left: y,
							width: width,
							height: height,
							userLogin: object.find('property[name=user_login] > value').text(),
							userId: object.find('property[name=user_id] > value').text(),
							id: ticketId
						}, true);
						
						new Message(userLogin+' отмечен на фотографии');
						
						Tickets.setTicketsZIndex();
					}
				});
			}
		});
	},
	
	startResize: function(direct) {
		var __self = this;
		
		$('#photo_ticket_temp > .resize').hide();
		$('#ticket_form').hide();
		
		$(document)
			.bind('mousemove', {direction: direct}, this.resize)
			.bind('mouseup', function() {
				$(document).unbind('mousemove', __self.resize)
				__self.stopResize();
			});
	},
	
	stopResize: function() {
		var ticketsWrapper = $('#photo_tickets');
		var ticket = $('#photo_ticket_temp');
		var area = $('#photo_ticket_temp > .area');
		
		$('#photo_ticket_temp > .resize').show();
		ticketsWrapper.css('cursor', 'auto');
		area.css('cursor', 'move');
		
		$('#ticket_form').show();
		this.updateFormPosition();
		
		if (area.height() < Tickets.settings.minHeight) {
			if (ticket.offset().top + Tickets.settings.minHeight > ticketsWrapper.offset().top + ticketsWrapper.height()) {
				area.height(Tickets.settings.minHeight);
				ticket.css('top', (ticketsWrapper.height() - Tickets.settings.minHeight) + 'px');
				this.updatePhotoCrop();
			} else {
				area.height(Tickets.settings.minHeight);
			}
		}
		
		if (area.width() < Tickets.settings.minWidth) {
			if (ticket.offset().left + Tickets.settings.minWidth > ticketsWrapper.offset().left + ticketsWrapper.width()) {
				area.width(Tickets.settings.minWidth);
				ticket.css('left', (ticketsWrapper.width() - Tickets.settings.minWidth) + 'px');
				this.updatePhotoCrop();
			} else {
				area.width(Tickets.settings.minWidth);
			}
		}
	},
	
	changeResize: function(direct) {
		$(document).bind('mousemove', {direction: direct}, this.resize)
	},
	
	updatePhotoCrop: function() {
		var ticket = $('#photo_ticket_temp');
		
		$('#photo_ticket_temp > .area').css('background-position', '-'+(ticket.position().left)+'px -'+(ticket.position().top)+'px');
	},
	
	resize: function(e) {
		$(document).unbind('mousemove', Tickets.move);
		
		var ticket = $('#photo_ticket_temp');
		var ticketOffset = ticket.offset();
		var ticketTop = ticketOffset.top;
		var ticketLeft = ticketOffset.left;
		
		var area = $('#photo_ticket_temp > .area');
		var areaHeight = area.height();
		var areaWidth = area.width();
		
		var ticketsWrapper = $('#photo_tickets');
		var ticketsWrapperOffset = ticketsWrapper.offset();
		var ticketsWrapperTop = ticketsWrapperOffset.top;
		var ticketsWrapperLeft = ticketsWrapperOffset.left;
		var ticketsWrapperHeight = ticketsWrapper.height();
		var ticketsWrapperWidth = ticketsWrapper.width();
		
		// Направление движения курсора
		var verticalDirection = e.pageY < ticketTop ? 'top' : 'bottom';
		var horisontalDirection = e.pageX < ticketLeft ? 'left' : 'right';
		
		var resizeTop = function() {
			if (e.pageY < ticketsWrapperTop) {
				ticket.css('top', '0');
				area.height(areaHeight + (ticketTop - ticketsWrapperTop));
			}
			else if (e.pageY > ticketTop + areaHeight) {
				switch(e.data.direction) {
					case 'nw' : Tickets.changeResize('sw'); return false;
					case 'ne' : Tickets.changeResize('se'); return false;
				}
			}
			else {
				ticket.css('top', (e.pageY - ticketsWrapperTop) + 'px');
				area.height(areaHeight - (ticket.offset().top - ticketTop));
			}
			
			return true;
		};
		
		var resizeBottom = function() {
			if (e.pageY > ticketsWrapperTop + ticketsWrapperHeight) {
				area.height(ticketsWrapperTop + ticketsWrapperHeight - ticket.offset().top);
			}
			else if (e.pageY < ticketTop) {
				switch(e.data.direction) {
					case 'sw' : Tickets.changeResize('nw'); return false;
					case 'se' : Tickets.changeResize('ne'); return false;
				}
			}
			else {
				area.height(e.pageY - ticketTop);
			}
			
			return true;
		};
		
		var resizeLeft = function() {
			if (e.pageX < ticketsWrapperLeft) {
				ticket.css('left', '0');
				area.width(areaWidth - (ticket.offset().left - ticketLeft));
			}
			else if (e.pageX > ticketLeft + areaWidth) {
				switch(e.data.direction) {
					case 'nw' : Tickets.changeResize('ne'); return false;
					case 'sw' : Tickets.changeResize('se'); return false;
				}
			}
			else {
				ticket.css('left', (e.pageX - ticketsWrapperLeft) + 'px');
				area.width(areaWidth - (ticket.offset().left - ticketLeft));
			}
			
			return true;
		};
		
		var resizeRight = function() {
			if (e.pageX > ticketsWrapperLeft + ticketsWrapperWidth) {
				area.width(ticketsWrapperLeft + ticketsWrapperWidth - ticket.offset().left);
			}
			else if (e.pageX < ticketLeft) {
				switch(e.data.direction) {
					case 'ne' : Tickets.changeResize('nw'); return false;
					case 'se' : Tickets.changeResize('sw'); return false;
				}
			}
			else {
				area.width(e.pageX - ticket.offset().left);
			}
			
			return true;
		};
		
		switch (e.data.direction) {
			case 'nw': {
				ticketsWrapper.css('cursor', 'nw-resize');
				area.css('cursor', 'nw-resize');
				
				if (!resizeTop()) {
					return;
				}
				
				if (!resizeLeft()) {
					return;
				}
				
				break;
			}
			case 'ne': {
				ticketsWrapper.css('cursor', 'ne-resize');
				area.css('cursor', 'ne-resize');
				
				if (!resizeTop()) {
					return;
				}
				
				if (!resizeRight()) {
					return;
				}
				
				break;
			}
			case 'se': {
				ticketsWrapper.css('cursor', 'se-resize');
				area.css('cursor', 'se-resize');
				
				if (!resizeBottom()) {
					return;
				}
				
				if (!resizeRight()) {
					return;
				}
				
				break;
			}
			case 'sw': {
				ticketsWrapper.css('cursor', 'sw-resize');
				area.css('cursor', 'sw-resize');
				
				if (!resizeBottom()) {
					return;
				}
				
				if (!resizeLeft()) {
					return;
				}
				
				break;
			}
		}
		
		Tickets.updatePhotoCrop();
	},
	
	startMove: function(e) {
		$('#photo_image').disableTextSelect();
		$('#photo_ticket_temp > .resize').hide();
		$('#ticket_form').hide();
		$('#photo_tickets').css('cursor', 'move');
		
		var data = {
			paddingTop: e.pageY - $('#photo_ticket_temp').offset().top,
			paddingLeft: e.pageX - $('#photo_ticket_temp').offset().left
		};
		
		$(document).bind('mousemove', data, this.move);
	},
	
	stopMove: function() {
		$('#photo_ticket_temp > .resize').show();
		$('#photo_tickets').css('cursor', 'auto');
		
		$('#ticket_form').show();
		this.updateFormPosition();
		
		$(document).unbind('mousemove', this.move);
	},
	
	move : function(e) {
		var ticket = $('#photo_ticket_temp');
		var ticketOffset = ticket.offset();
		
		var ticketsWrapper = $('#photo_tickets');
		var ticketsWrapperOffset = ticketsWrapper.offset();
		
		var newTop = e.pageY - ticketsWrapperOffset.top - e.data.paddingTop;
		var newLeft = e.pageX - ticketsWrapperOffset.left - e.data.paddingLeft;
		
		if (
			   e.pageY - e.data.paddingTop > ticketsWrapperOffset.top
			&& e.pageY - e.data.paddingTop + ticket.height() < ticketsWrapperOffset.top + ticketsWrapper.height()
		){
			ticket.css('top', newTop+'px');
		}
		else if ( e.pageY - e.data.paddingTop < ticketsWrapperOffset.top) {
			ticket.css('top', '0px');
		}
		else {
			ticket.css('top', (ticketsWrapper.height()-ticket.height())+'px');
		}
		
		if (
			   e.pageX - e.data.paddingLeft > ticketsWrapperOffset.left
			&& e.pageX - e.data.paddingLeft + ticket.width()  < ticketsWrapperOffset.left + ticketsWrapper.width()
		){
			ticket.css('left', newLeft+'px');
		}
		else if ( e.pageX - e.data.paddingLeft < ticketsWrapperOffset.left) {
			ticket.css('left', '0px');
		}
		else {
			ticket.css('left', (ticketsWrapper.width()-ticket.width())+'px');
		}
		
		Tickets.updatePhotoCrop();
	}
};